﻿using System;
using System.Web.Mvc;
using Oxite.Extensions;
using Oxite.Models;
using ECube.Web.CMS.Models;
using ECube.Web.CMS.Services;
using ECube.Web.CMS.Extensions;
using Oxite.Validation;
using Oxite.ViewModels;

namespace ECube.Web.CMS.Controllers
{
    public class SitePageController : Controller
    {
        private readonly IPageService pageService;

        public SitePageController(IPageService pageService)
        {
            this.pageService = pageService;
            ValidateRequest = false;
        }

        public OxiteViewModelItems<Page> List()
        {
            return new OxiteViewModelItems<Page>(pageService.GetPages());
        }

        public Page Item(Page page)
        {
            //TODO: (erikpo) Check permissions to see if the current user is allowed to see this page or not
            return page;
        }

        [HttpPost]
        public ActionResult Validate(PageInput pageInput)
        {
            ValidationStateDictionary validationState = pageService.ValidatePageInput(pageInput);

            if (validationState.IsValid) return Content("");

            return PartialView("ValidationErrors", new OxiteViewModelPartial<ValidationStateDictionary>(new OxiteViewModel(), validationState));
        }

        [ActionName("ItemAdd"), HttpGet]
        public PageInput Add(PageInput pageInput)
        {
            //TODO: (erikpo) Check permissions

            return new PageInput(
                pageInput != null ? pageInput.TemplateName : "",
                pageInput != null ? pageInput.Title : "",
                pageInput != null ? pageInput.Description : "",
                pageInput != null ? pageInput.Slug : "",
                pageInput != null ? pageInput.Published : null
                );
        }

        [ActionName("ItemAdd"), HttpPost]
        public object AddSave(Page page,PageInput pageInput)
        {
            //TODO: (erikpo) Check permissions

            ModelResult<Page> results = Save(page, pageInput);

            if (!results.IsValid)
            {
                ModelState.AddModelErrors(results.ValidationState);

                return Add(pageInput);
            }
            object url="";
            this.RouteData.Values.TryGetValue("pagePath", out url);
            return Redirect(Url.AppPath("~/" + url.ToString()));
        }

        [ActionName("ItemDesign"), HttpGet]
        public Page Design(Page page)
        {
            if (page == null) return null;

            //TODO: (erikpo) Check permissions

            page.Profile.IsDesign = true;

            //ViewData["Skin"] = "Admin";            

            //var model = new OxiteViewModelItem<PageInput>(new PageInput(page, pageInput));

           // model.AddModelItem(page);

            return page;
        }

        [ActionName("ItemDesign"), HttpPost]
        public object SaveDesign(Page page, PageProfile pageProfile)
        {
            if (page == null) return null;

            //TODO: (erikpo) Check permissions
            page.Profile = pageProfile;
            ;

            if (!pageService.SavePageDesign(page))
            {
                ModelState.AddModelError("pageprofile","保存失败！");                             
                
            }
            return Design(page);               
        }
        [ActionName("ItemEdit"), HttpGet]
        public Page Edit(Page page)
        {
            if (page == null) return null;
            page.IsEdit = true;
            return page;
        }

        [ActionName("ItemEdit"), HttpPost]
        public object SaveEdit(Page page, PageInput pageInput)
        {
            if (page == null) return null;

            //TODO: (erikpo) Check permissions

            ModelResult<Page> results = pageService.EditPage(page, pageInput);

            if (!results.IsValid)
            {
                ModelState.AddModelErrors(results.ValidationState);

            }
            
            return Edit(page); 
        }

        [ActionName("ItemAddContent"), HttpPost]
        public object SaveAddContent(Page page, ContentItemInput contentItemInput)
        {
            if (page == null) return null;

            //TODO: (erikpo) Check permissions

            pageService.AddPageContent(page, contentItemInput);

            //todo: (nheskew) get this all set up to edit a single content item and link back down to that content. probably needs a success message too
            return Redirect(Url.Page(page));
        }

        [ActionName("ItemEditContent"), HttpPost]
        public object SaveEditContent(Page page, ContentItemsInput contentItemsInput)
        {
            if (page == null) return null;

            //TODO: (erikpo) Check permissions

            pageService.EditPageContent(page, contentItemsInput);

            //todo: (nheskew) get this all set up to edit a single content item and link back down to that content. probably needs a success message too
            return Redirect(Url.Page(page));
        }

        [HttpPost]
        public ActionResult Remove(Page page, string returnUri)
        {
            if (page == null) return null;

            //TODO: (erikpo) Check permissions

            pageService.RemovePage(page);
            

            return Redirect(returnUri);
        }
        [ActionName("EditMeta"), HttpGet]
        public ActionResult EditMeta(Page page)
        {
            PageInput input = null;
            if (page != null)
            {
                input = new PageInput(page, null);
            }
            return this.PartialView(this.Add(input));
        }
        [ActionName("EditMeta"),HttpPost]
        public ActionResult SaveEditMeta(Page page, PageInput input, string MvcSiteMapNodeId, string ActionMode)
        {
            if(!(ActionMode != null && ActionMode.Equals("Get")))
             {
                if (page == null) page = new Page(Guid.Empty) { SiteMapNodeKey = MvcSiteMapNodeId };

                Save(page, input);          
            }
            return this.PartialView(this.Add(input));
        }

        private ModelResult<Page> Save(Page page, PageInput input)
        {
            ModelResult<Page> results = (page == null || page.ID.Equals(Guid.Empty)) ? pageService.AddPage(input) : pageService.EditPage(page, input);

            if (!results.IsValid)
            {
                ModelState.AddModelErrors(results.ValidationState);
            }
            else if (!string.IsNullOrEmpty(page.SiteMapNodeKey))
            {
                MvcSiteMapNode node = SiteNavigatorService.Current.FindNode(page.SiteMapNodeKey) as MvcSiteMapNode;
                if (node != null)
                {
                    node.PageId = results.Item.ID.ToString();
                    SiteNavigatorService.Current.Save();
                }
            }
            return results;
 
        }


        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
            if (filterContext.Result is ViewResult)
            {
                string menu = string.Format(@"<li><a href=""{0}"">设计</a></li>",Url.Action("ItemDesign") + "?" + PageMode.Design.ToString() );
                menu += string.Format(@"<li><a href=""{0}"">编辑</a></li>",Url.Action("ItemEdit") + "?" + PageMode.Edit.ToString());
                this.ViewData.Add("ActionMenu",menu);
            }            
        }
    }
}
